export default {
  namespaced:true,
  state:() => ({
    // 购物车数据对象:  { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart:JSON.parse(uni.getStorageSync('cart') || '[]'),  //从本地存储中获取数据
  }),
  mutations:{
    addToCart(state,goods) {
      // 通过Id查找需加入购物车的商品在购物车中是否存在，若存在，则数量加1，若不存在，则整个对象都需要加进购物车
      const goodItem = state.cart.find(item => item.goods_id === goods.goods_id)
      if(!goodItem) {
        state.cart.push(goods)
      } else {
        goodItem.goods_count++
      }
      // console.log(state.cart)
      // 当购物车数量发生变化后，将本地数据进行更新
      this.commit('m_cart/saveToStorage')
    },
    // 将购物车数据持久化到本地
    saveToStorage(state) {
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 修改购物车商品的选中状态
    changeCartRadio(state,goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_state = goods.goods_state
        uni.setStorageSync('cart',JSON.stringify(state.cart))
      }
    },
    // 修改商品数量
    updateGoodsCount(state,goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    // 删除商品
    delGoodsById(state,goods_id) {
      state.cart = state.cart.filter(item => item.goods_id !== goods_id)
      this.commit('m_cart/saveToStorage')
    },
    // 全选按钮控制单选按钮
    updateAllGoodsState(state,newState) {
      state.cart.forEach(item => item.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    }
  },
  getters:{
    // 计算购物车中商品的数量
    total(state) {
      return state.cart.reduce((sum,item) => sum+item.goods_count,0)
    },
    // 计算购物车中选中商品的数量
    checkCount(state) {
      return state.cart.filter(item => item.goods_state).reduce((sum,item) => sum+item.goods_count,0)
    },
    // 计算选中商品的总价格
    totalPrice(state) {
      return state.cart.filter(item => item.goods_state).reduce((sum,item) => sum+item.goods_count*item.goods_price,0).toFixed(2)
    }
  },
}